package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

@WebServlet("/ServletRemove")
public class ServletRemove extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        HashMap<String, Student> hm = new HashMap<>();
        String realPath = getServletContext().getRealPath("/stu.txt");
        BufferedReader br = new BufferedReader(new FileReader(realPath));
        String s;
        while ((s=br.readLine())!=null){
            String[] split = s.split(":");
            hm.put(split[0],new Student(split[0],split[1],split[2],Integer.parseInt(split[3])));
        }
        br.close();
        hm.remove(name);//直接删除集合中的值
        BufferedWriter bw = new BufferedWriter(new FileWriter(realPath));
        Set<String> setlist = hm.keySet();
        for (String set : setlist) {
            Student student=hm.get(set);
            bw.write(student.getId()+":"+student.getName()+":"+student.getSex()+":"+student.getScore());
            bw.newLine();
            bw.flush();
        }
        bw.close();
        response.sendRedirect(request.getContextPath()+"/ServletFind");
    }
}
